﻿using HalconDotNet;
using Halcon二次开发.Model.储存每个Controller的单例对象;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Halcon二次开发.Controller.模板匹配;
using Halcon二次开发.Controller.Controller基类;
using Halcon二次开发.Model;
using Halcon二次开发.Model.储放所有单例.储存每个单例界面;
using Halcon二次开发.Model.工具区域的扩展类;
using System.Windows.Shapes;
using static System.Windows.Forms.LinkLabel;
using System.Diagnostics;
using System.Windows.Forms;
using System.IO;
using Halcon二次开发.View.卡尺;
using Halcon二次开发.Tools;

namespace Halcon二次开发.Controller.卡尺
{
    /// <summary>
    /// 精准测量卡尺
    /// </summary>
    public class Caliper
    {

        /// <summary>
        /// 该工具的线段对象
        /// </summary>
        List<HDrawingObjectEx> lines = new List<HDrawingObjectEx>();
        /// <summary>
        /// 卡尺界面
        /// </summary>
        PreciseCaliper form;
        /// <summary>
        /// 卡尺校验保存数据
        /// </summary>
        string path;
        HTuple hv_Row, hv_Column, hv_Phi, hv_Length1, hv_Length2;
        HObject ho_ROI_1;
        /// <summary>
        /// 该工具的线段对象
        /// </summary>
        HDrawingObjectEx line;
        /// <summary>
        /// 当前控件对象
        /// </summary>
        HSmartWindowControl hw;

        /// 移动事件更改数据禁止
        /// </summary>
        bool check = false;
        /// <summary>
        /// 有没有放置
        /// </summary>
        bool putCheck = false;
        /// <summary>
        /// 模式选择
        /// </summary>
        ComboBox combox1;
        
        /// <summary>
        /// 位置-旋转-长度1-长度2
        /// </summary>
        NumericUpDown numericUpDown1, numericUpDown2, numericUpDown3,numericUpDown7, numericUpDown10;

        /// <summary>
        /// 标注图形,用于第一次画显示在模板的第一个元素上面
        /// </summary>
        public HObject ho_Biaozhu;

        /// <summary>
        /// 偏移量 - 第一个模板的数据  第一个绘制的线段数据 
        /// </summary>
        public double firstModel_y, firstModel_x, firstModel_phi;
        #region 控制参数
        /// <summary>
        /// 输入图像
        /// </summary>
        public HObject HideIntputImage;
        /// <summary>
        /// 输入的行-列-角度 坐标
        /// </summary>
        public double[] HideOutputArrayRows, HideIntputArrayColumns, HideIntputArrayPhis;
        /// <summary>
        /// 卡尺的位置  - 输出点 - 距离 
        /// </summary>
        public double HideIntputX, HideIntputY, HideIntputPhi, HideIntputLength1, HideIntputLength2, HideOutputX1, HideOutputY1, HideOutputX2, HideOutputY2;

        /// <summary>
        /// 输出的距离数组
        /// </summary>
        public double[] HideOutputArrayDistances;

        /// <summary>
        /// 卡尺的宽度,高度,对比度,平滑度
        /// </summary>
        public double HideIntputWidth = 0, HideIntputHeight = 0, HideIntputThreshold, HideIntputSigma;
        /// <summary>
        /// 颜色样式
        /// </summary>
        public string HideOutputBorderColor, HideOutputCenterConlor, HideOutputlineColor = "red";
        #endregion
        public Caliper(string path,PreciseCaliper form) {
            //获取当前工位
            hw = StaicResouce.HwindowFlowNodeUrse.hSmartWindowControl1;
            this.path = path;
            this.form = form;
        }

        /// <summary>
        /// 画矩形
        /// </summary>
        /// <param name="hv_WindowHandle">句柄</param>
        /// <param name="ho_ROI_0">画的区域</param>
        public void DrawRecangle(NumericUpDown numericUpDown1, NumericUpDown numericUpDown2, NumericUpDown numericUpDown3, NumericUpDown numericUpDown7,NumericUpDown numericUpDown10, 
            NumericUpDown numericUpDown4, NumericUpDown numericUpDown8, NumericUpDown numericUpDown9,
            NumericUpDown numericUpDown6, NumericUpDown numericUpDown5, 
            TextBox textBox1, TextBox textBox2,TextBox textBox3,ComboBox combox1) {
            ClearObject();

            HideOutputlineColor = textBox3.Text;
            //这里要标注区域
            if (HideOutputArrayRows != null&& HideOutputArrayRows.Length>0)
            {
                HOperatorSet.SetColor(hw.HalconWindow, "red");
                HOperatorSet.SetDraw(hw.HalconWindow, "fill");
                HOperatorSet.GenCircle(out ho_Biaozhu, HideOutputArrayRows[0], HideIntputArrayColumns[0], 20);
                HOperatorSet.DispObj(ho_Biaozhu, hw.HalconWindow);
                HOperatorSet.SetColor(hw.HalconWindow, HideOutputlineColor.ToLower());
                HOperatorSet.SetDraw(hw.HalconWindow, "margin");
            }
            
            //定义绘制线的开始坐标与结束坐标
            var lineTuple = new HTuple[] { 50, 100, 0, 100,100};
            //创建线的对象
            HDrawingObject lineObj = HDrawingObject.CreateDrawingObject(HDrawingObject.HDrawingObjectType.RECTANGLE2, lineTuple);
            //设置线的颜色
            try
            {
                lineObj.SetDrawingObjectParams("color", HideOutputlineColor.ToLower());
            }
            catch
            {
                lineObj.SetDrawingObjectParams("color", "red");
                throw new Exception("该线条不支持此颜色以为你选择默认颜色!");
                
            }
            //线段拖动触发事件注册
            lineObj.OnDrag(LineOnDrag);
            //线段长度修改触发事件注册
            lineObj.OnResize(LineOnResize);

            //永久保留该对象,不然会被垃圾回收机制回收
            line = new HDrawingObjectEx
            {
                HDrawingObject = lineObj,
                hTuples = lineTuple
            };
            //增加这个对象到指定Halcon窗口
            hw.HalconWindow.AttachDrawingObjectToWindow(lineObj);
            //输入
            HideIntputX = double.Parse(numericUpDown1.Value + "");
            HideIntputY = double.Parse(numericUpDown2.Value + "");
            HideIntputPhi = double.Parse(numericUpDown3.Value + "");
            HideIntputLength1 = double.Parse(numericUpDown7.Value + "");
            HideIntputLength2 = double.Parse(numericUpDown10.Value + "");

            this.numericUpDown1 = numericUpDown1;
            this.numericUpDown2 = numericUpDown2;
            this.numericUpDown3 = numericUpDown3;
            this.numericUpDown7 = numericUpDown7;
            this.numericUpDown10 = numericUpDown10;

            this.HideIntputThreshold = double.Parse(numericUpDown8.Value + "");
            this.HideIntputSigma = double.Parse(numericUpDown9.Value + "");
            this.HideIntputHeight = double.Parse(numericUpDown5.Value + "");
            this.HideIntputWidth = double.Parse(numericUpDown6.Value + "");
            this.HideOutputBorderColor = textBox1.Text;
            this.HideOutputCenterConlor = textBox2.Text;
            this.HideOutputlineColor = textBox3.Text;
            this.combox1 = combox1;

            //写入校验数据
            //创建目录检查
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            string path1 = path + $"\\{form.Text}.txt";
            using (FileStream sw = new FileStream(path1, FileMode.Create, FileAccess.Write))
            {
                sw.Write(Encoding.UTF8.GetBytes(false.ToString()), 0, Encoding.UTF8.GetBytes(putCheck.ToString()).Length);
            }
        }
        /// <summary>
        /// 线段拖动触发事件
        /// </summary>
        /// <param name="drawid"></param>
        /// <param name="window"></param>
        /// <param name="type"></param>
        public void LineOnDrag(HDrawingObject drawid, HWindow window, string type)
        {
            UpdataDrawingObjecData(drawid);
        }
        /// <summary>
        /// 线段长度修改触发事件
        /// </summary>
        /// <param name="drawid"></param>
        /// <param name="window"></param>
        /// <param name="type"></param>
        public void LineOnResize(HDrawingObject drawid, HWindow window, string type)
        {
            UpdataDrawingObjecData(drawid);
        }
        /// <summary>
        /// 线段拖动修改长度方法
        /// </summary>
        /// <param name="drawid"></param>
        public void UpdataDrawingObjecData(HDrawingObject drawid)
        {
            //创建一个要得到对象属性的元组
            var attTuple = new HTuple("row", "column", "phi", "length1", "length2");
            //获取对应的属性
            var valueTuple = drawid.GetDrawingObjectParams(attTuple);
            //对对应的属性进行封装一下,后面好加入到集合中
            var attValues = new HTuple[] { valueTuple[0], valueTuple[1], valueTuple[2], valueTuple[3] , valueTuple[4] };
            //更新数据
            line.hTuples = attValues;
            this.numericUpDown1.Value = decimal.Parse(valueTuple[1].D.ToString());
            this.numericUpDown2.Value = decimal.Parse(valueTuple[0].D.ToString());
            this.numericUpDown3.Value = decimal.Parse(valueTuple[3].D.ToString());
            //这里弧度会失败
            if (decimal.TryParse(valueTuple[4].D.ToString(), out decimal result1))
            {
                this.numericUpDown7.Value = result1;
            }
            if (decimal.TryParse(valueTuple[2].D.ToString(), out decimal result2))
            {
                this.numericUpDown10.Value = result2;
            }

            //写入校验数据
            //创建目录检查
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            string path1 = path + $"\\{form.Text}.txt";
            using (FileStream sw = new FileStream(path1, FileMode.Create, FileAccess.Write))
            {
                sw.Write(Encoding.UTF8.GetBytes(false.ToString()), 0, Encoding.UTF8.GetBytes(putCheck.ToString()).Length);
            }

        }
        /// <summary>
        /// 清除这个线对象
        /// </summary>
        public void ClearObject()
        {
            if (lines!=null&&lines.Count>0) {
                foreach (HDrawingObjectEx line in lines) {
                    var ho = line.HDrawingObject;
                    if (ho.ID == 0) { continue; }
                    hw.HalconWindow.DetachDrawingObjectFromWindow(ho);
                    ho.Dispose();
                }
            }
            if (line == null) return;
            var hobject = line.HDrawingObject;
            if (hobject.ID ==0) { return; }
            hw.HalconWindow.DetachDrawingObjectFromWindow(hobject);
            hobject.Dispose();
        }

        /// <summary>
        /// 放置卡尺
        /// </summary>
        private double skewing_X;  //偏移量X
        private double skewing_Y;//偏移量Y
        private double skewing_Angle;//偏移量角度

        public void SetCaliper() 
        {
            if (HideIntputImage == null || ImageIsNg())
            {
                throw new Exception("当前图像为空");
            }
            
            HWindow hv_WindowHandle = hw.HalconWindow;
            //设置halcon图像模式
            HOperatorSet.SetSystem("clip_region", "false");
            HOperatorSet.GenRectangle2(out ho_ROI_1, HideIntputY, HideIntputX, HideIntputPhi, HideIntputLength1, HideIntputLength2);
            //清除这个模型  
            ClearObject();
            HOperatorSet.SetColor(hv_WindowHandle, "green");
            HOperatorSet.SetDraw(hv_WindowHandle, "margin");
            HOperatorSet.DispObj(ho_ROI_1, hv_WindowHandle);
            //放置了卡尺为true
            putCheck = true;

            //计算偏移
            if (HideOutputArrayRows != null && HideOutputArrayRows.Length > 0)
            {
                firstModel_y= HideIntputArrayColumns[0];
                firstModel_x = HideOutputArrayRows[0];
                firstModel_phi = HideIntputArrayPhis[0];
                form.numericUpDown13.Value = decimal.Parse((HideIntputArrayPhis[0] - HideIntputPhi).ToString());
            }
            //写入校验数据
            //创建目录检查
            if (!Directory.Exists(path)) { 
                Directory.CreateDirectory(path);    
            }
            string path1 = path+$"\\{form.Text}.txt";
            using (FileStream sw = new FileStream(path1, FileMode.Create,FileAccess.Write))
            {
                sw.Write(Encoding.UTF8.GetBytes(putCheck.ToString() + $",{firstModel_x},{firstModel_y},{firstModel_phi}"),0, Encoding.UTF8.GetBytes(putCheck.ToString()+$",{firstModel_x},{firstModel_y},{firstModel_phi}").Length);
            }
        }

        /// <summary>
        /// 运行
        /// </summary>
        public void Run() {
            if (HideIntputImage == null)
            {
                throw new Exception("当前输入图像为空!");
            }
            //先清除原本的Dataview集合
            form.dataGridView1.Rows.Clear();
            ClearObject();
            string[] strdb = new string[20];
            // 读取校验数据
            string path1 = path+$"\\{form.Text}.txt";
            bool putCheck = false;
            byte[] data = new byte[1024 * 1024 * 2];
            HWindow hv_WindowHandle = hw.HalconWindow;
            try 
            {
                using (FileStream sw = new FileStream(path1, FileMode.Open, FileAccess.Read))
                {
                    int index = sw.Read(data, 0, data.Length);
                    strdb = Encoding.UTF8.GetString(data, 0, index).Split(',');
                    putCheck = bool.Parse(strdb[0].ToLower());
                }
            }
            catch { 
                
            }
            //放置了卡尺
            if (putCheck)
            {
                ///多目标测量
                if (HideOutputArrayRows != null&& HideOutputArrayRows.Length > 0)
                {
                    //画多个卡尺工具跟随模板
                    DrawRectangle2s(HideIntputArrayColumns, HideOutputArrayRows, HideIntputArrayPhis, double.Parse((HideIntputArrayPhis[0] - HideIntputPhi).ToString()), strdb);
                }
                ///单次执行
                else {
                    HideOutputArrayDistances = new double[1];
                    try
                    {
                        HOperatorSet.SetColor(hv_WindowHandle, form.textBox1.Text.ToLower());
                    }
                    catch
                    {
                        HOperatorSet.SetColor(hw.HalconWindow, "red");
                        throw new Exception("该线条不支持此颜色以为你选择默认颜色!");
                    }
                    
                    HOperatorSet.GetImageSize(HideIntputImage, out HTuple hv_Width, out HTuple hv_Height);

                    HOperatorSet.GenMeasureRectangle2(HideIntputY, HideIntputX, HideIntputPhi, HideIntputLength1,
                        HideIntputLength2, hv_Width, hv_Height, "bilinear", out HTuple hv_MeasureHandle);
                    ClearObject();
                    try
                    {
                        try
                        {
                            HOperatorSet.SetColor(hw.HalconWindow, form.textBox3.Text.ToLower());
                        }
                        catch
                        {
                            HOperatorSet.SetColor(hw.HalconWindow, "red");
                            throw new Exception("该线条不支持此颜色以为你选择默认颜色!");
                        }

                        //自动模式
                        if (form.comboBox1.SelectedItem.ToString() == "auto")
                        {
                            //高斯 边缘阈值 浅色深色选择
                            HOperatorSet.MeasurePos(HideIntputImage, hv_MeasureHandle, this.HideIntputSigma, this.HideIntputThreshold, "positive",
                                "all", out HTuple hv_RowEdge, out HTuple hv_ColumnEdge, out HTuple hv_Amplitude, out HTuple hv_Distance);
                            if (hv_Distance.Length == 0)
                            {
                                HOperatorSet.MeasurePos(HideIntputImage, hv_MeasureHandle, this.HideIntputSigma, this.HideIntputThreshold, "negative",
                                "all", out hv_RowEdge, out hv_ColumnEdge, out hv_Amplitude, out hv_Distance);
                            }

                            if (hv_Distance.Length == 0)
                            {

                                HideOutputArrayDistances[0] = 0;
                                form.dataGridView1.Rows.Add(0, 0);
                                throw new Exception("无法查找到边缘! Caliper-line-236!");
                            }
                            else
                            {
                                HideOutputArrayDistances[0] = hv_Distance[0].D;
                                form.dataGridView1.Rows.Add(0, hv_Distance[0].D);
                                //画2个点之间的距离  distance:2点之间的距离
                                HOperatorSet.GenRegionLine(out HObject regionLines, hv_RowEdge[0], hv_ColumnEdge[0], hv_RowEdge[1], hv_ColumnEdge[1]);
                                //将线显示在图像上
                                HOperatorSet.DispObj(regionLines, hw.HalconWindow);

                            }
                        }
                        else
                        {
                            //高斯 边缘阈值 浅色深色选择
                            HOperatorSet.MeasurePos(HideIntputImage, hv_MeasureHandle, this.HideIntputSigma, this.HideIntputThreshold, form.comboBox1.SelectedItem.ToString(),
                                "all", out HTuple hv_RowEdge, out HTuple hv_ColumnEdge, out HTuple hv_Amplitude, out HTuple hv_Distance);

                            //距离
                            if (hv_Distance.Length == 0)
                            {
                                HideOutputArrayDistances[0] = 0;
                                form.dataGridView1.Rows.Add(0, 0);
                                throw new Exception("无法查找到边缘! Caliper-line-236!");
                            }
                            else
                            {
                                HideOutputArrayDistances[0] = hv_Distance[0].D;
                                form.dataGridView1.Rows.Add(0, hv_Distance[0].D);
                                //画2个点之间的距离  distance:2点之间的距离
                                HOperatorSet.GenRegionLine(out HObject regionLines, hv_RowEdge[0], hv_ColumnEdge[0], hv_RowEdge[1], hv_ColumnEdge[1]);

                                //将线显示在图像上
                                HOperatorSet.DispObj(regionLines, hw.HalconWindow);

                                //HOperatorSet.SetColor(hv_WindowHandle, "red");
                                //HOperatorSet.DispCross(hv_WindowHandle, hv_RowEdge, hv_ColumnEdge, 100, (new HTuple(60)).TupleRad());
                            }
                            HideOutputArrayDistances[0] = hv_Distance;
                        }
                    }
                    catch (Exception ex)
                    {
                        string str = ex.Message.Contains("无法查找到边缘") ? ex.Message : "精准测量工具运行失败 Caliper-line-241!";
                        throw new Exception(str);
                    }
                }
            }
            //没有放置
            else {
                ClearObject();
                throw new Exception("请先放置卡尺!");
            }
        }

        /// <summary>
        /// shuzhi移动
        /// </summary>
        public void Move_X(double x1, double y1, double phi,double length1,double length2)
        {
            ClearObject();
            HideIntputX = x1;
            HideIntputY = y1;
            HideIntputPhi = phi;
            HideIntputLength1 = length1;
            HideIntputLength2 = length2;
            //定义绘制线的开始坐标与结束坐标
            var lineTuple = new HTuple[] { y1, x1, phi, length1 , length2};
            //创建线的对象
            var lineObj = HDrawingObject.CreateDrawingObject(HDrawingObject.HDrawingObjectType.RECTANGLE2, lineTuple);
            //线段拖动触发事件注册
            lineObj.OnDrag(LineOnDrag);
            //线段长度修改触发事件注册
            lineObj.OnResize(LineOnResize);

            //设置线的颜色
            try
            {
                lineObj.SetDrawingObjectParams("color", HideOutputlineColor.ToLower());
            }
            catch
            {
                (FormDb.Db["Form1"] as Form1).textBox1.AppendText("该线条不支持此颜色以为你选择默认颜色!\r\n");
                lineObj.SetDrawingObjectParams("color", "red");
            }

            //永久保留该对象,不然会被垃圾回收机制回收
            line = new HDrawingObjectEx
            {
                HDrawingObject = lineObj,
                hTuples = lineTuple
            };
            //增加这个对象到指定Halcon窗口
            hw.HalconWindow.AttachDrawingObjectToWindow(lineObj);
        }
        /// <summary>
        /// 修改平滑与对比度
        /// </summary>
        /// <param name="sigam"></param>
        /// <param name="threshold"></param>
        public void Updata_SigamThreshold(double sigam,double threshold) {
            this.HideIntputSigma = sigam;
            this.HideIntputThreshold = threshold;
        }

        /// <summary>
        /// 工具的单次运行
        /// </summary>
        public void Tool_Run() {

            if (HideIntputImage == null|| ImageIsNg())
            {
                throw new Exception("当前图像为空");
            }
            hw.HalconWindow.ClearWindow();
            HOperatorSet.DispObj(HideIntputImage, hw.HalconWindow);
            Run();
        }
        public bool ImageIsNg()
        {
            foreach (TreeNode node in StaicResouce.HwindowFlowNodeUrse.treeView1.Nodes)
            {
                if (node.Nodes.Count == 0) continue;
                if (node.Nodes[0].Tag == this && node.Nodes[0].Text.Contains("<—"))
                {
                    return false;
                }
            }
            return true;
        }

        /// <summary>z
        /// 创建多个旋转矩形,根据模板的识别出的数据决定
        /// </summary>
        public void DrawRectangle2s(double[] IntputColums, double[] IntputRows, double[] IntputAngles,double PianYiPhi, string[] strdb)
        {
            //声明数组长度
            int Dbcount = 0;
            HideOutputArrayDistances = new double[IntputColums.Length];

            HWindow hwindow =  hw.HalconWindow;
            lines.Clear();
            for (int i = 0; i < IntputColums.Length; i++)
            {
                //创建线的对象
                HOperatorSet.GenRectangle2(out HObject hLine, double.Parse(form.numericUpDown2.Value.ToString()), double.Parse(form.numericUpDown1.Value.ToString()), double.Parse(form.numericUpDown10.Value.ToString()),
                    double.Parse(form.numericUpDown3.Value.ToString()), double.Parse(form.numericUpDown7.Value.ToString()));

                HObject ho_RegionAffineTrans = UtiyHalcon.MatrixCalculate(hLine, IntputRows[i], IntputColums[i], IntputAngles[i], double.Parse(strdb[1]), double.Parse(strdb[2]), double.Parse(strdb[3]));

                //获取矩形的位置信息
                HOperatorSet.SmallestRectangle2(ho_RegionAffineTrans,out HTuple row, out HTuple col, out HTuple phi, out HTuple length1, out HTuple length2);
                //显示出每个卡尺
                try
                {
                    HOperatorSet.SetColor(hwindow, form.textBox3.Text.ToLower());    
                }
                catch
                {
                    HOperatorSet.SetColor(hwindow, "red");
                    throw new Exception("该线条不支持此颜色以为你选择默认颜色!");
                }
                HOperatorSet.SetDraw(hwindow,"margin");
                HOperatorSet.DispRectangle2(hwindow,row,col,phi,length1,length2);
                HOperatorSet.SetDraw(hwindow,"fill");

                //开始计算距离
                HOperatorSet.GetImageSize(HideIntputImage, out HTuple hv_Width, out HTuple hv_Height);

                HOperatorSet.GenMeasureRectangle2(row, col, phi, length1,
                    length2, hv_Width, hv_Height, "bilinear", out HTuple hv_MeasureHandle);
                ClearObject();
                try
                {
                    //自动模式
                    if (form.comboBox1.SelectedItem.ToString() == "auto")
                    {
                        //高斯 边缘阈值 浅色深色选择
                        HOperatorSet.MeasurePos(HideIntputImage, hv_MeasureHandle, this.HideIntputSigma, this.HideIntputThreshold, "positive",
                            "all", out HTuple hv_RowEdge, out HTuple hv_ColumnEdge, out HTuple hv_Amplitude, out HTuple hv_Distance);
                        if (hv_Distance.Length == 0)
                        {
                            HOperatorSet.MeasurePos(HideIntputImage, hv_MeasureHandle, this.HideIntputSigma, this.HideIntputThreshold, "negative",
                            "all", out hv_RowEdge, out hv_ColumnEdge, out hv_Amplitude, out hv_Distance);

                        }

                        try
                        {
                            HOperatorSet.SetColor(hwindow, form.textBox1.Text.ToLower());
                        }
                        catch
                        {
                            HOperatorSet.SetColor(hwindow, "red");
                            throw new Exception("该线条不支持此颜色以为你选择默认颜色!");
                        }


                        if (hv_Distance.Length == 0)
                        {

                            HideOutputArrayDistances[Dbcount] = 0;
                            form.dataGridView1.Rows.Add(Dbcount, 0);
                            Dbcount++;
                            //throw new Exception("无法查找到边缘! Caliper-line-236!");
                        }
                        else
                        {
                            //画2个点之间的距离  distance:2点之间的距离
                            HOperatorSet.GenRegionLine(out HObject regionLines, hv_RowEdge[0], hv_ColumnEdge[0], hv_RowEdge[1], hv_ColumnEdge[1]);
                            //将线显示在图像上
                            HOperatorSet.DispObj(regionLines, hw.HalconWindow);
                            ///这里只要第0的下标的距离数据,因为卡尺会卡住多个边,不能精确到那条数据
                            HideOutputArrayDistances[Dbcount] = hv_Distance[0].D;
                            form.dataGridView1.Rows.Add(Dbcount, hv_Distance[0].D);
                            Dbcount++;

                        }
                        

                        

                        //HOperatorSet.DispCross(hv_WindowHandle, hv_RowEdge, hv_ColumnEdge, 10, (new HTuple(90)).TupleRad());
                    }
                    else
                    {
                        //高斯 边缘阈值 浅色深色选择
                        HOperatorSet.MeasurePos(HideIntputImage, hv_MeasureHandle, this.HideIntputSigma, this.HideIntputThreshold, form.comboBox1.SelectedItem.ToString(),
                            "all", out HTuple hv_RowEdge, out HTuple hv_ColumnEdge, out HTuple hv_Amplitude, out HTuple hv_Distance);

                        //距离
                        if (hv_Distance.Length == 0)
                        {
                            HideOutputArrayDistances[Dbcount] = 0;
                            form.dataGridView1.Rows.Add(Dbcount, 0);
                            Dbcount++;
                        }
                        else
                        {
                            try
                            {
                                HOperatorSet.SetColor(hwindow, form.textBox1.Text.ToLower());
                            }
                            catch
                            {
                                HOperatorSet.SetColor(hwindow, "red");
                                throw new Exception("该线条不支持此颜色以为你选择默认颜色!");
                            }

                            //画2个点之间的距离  distance:2点之间的距离
                            HOperatorSet.GenRegionLine(out HObject regionLines, hv_RowEdge[0], hv_ColumnEdge[0], hv_RowEdge[1], hv_ColumnEdge[1]);

                            //将线显示在图像上
                            HOperatorSet.DispObj(regionLines, hw.HalconWindow);
                            HideOutputArrayDistances[Dbcount] = hv_Distance[0].D;
                            form.dataGridView1.Rows.Add(Dbcount, hv_Distance[0].D);
                            Dbcount++;
                        }
                        
                    }
                }
                catch (Exception ex)
                {
                    string str = ex.Message.Contains("无法查找到边缘") ? ex.Message : "精准测量工具运行失败 Caliper-line-241!";
                    throw new Exception(str);
                }
            }



            //lines.Clear();
            //for (int i = 0; i < IntputColums.Length; i++)
            //{
            //    //创建线的对象
            //    HOperatorSet.GenRectangle2(out HObject hLine, double.Parse(form.numericUpDown2.Value.ToString()), double.Parse(form.numericUpDown1.Value.ToString()), double.Parse(form.numericUpDown10.Value.ToString()),
            //        double.Parse(form.numericUpDown3.Value.ToString()), double.Parse(form.numericUpDown7.Value.ToString()));


            //    HObject ho_RegionAffineTrans = UtiyHalcon.MatrixCalculate(hLine, IntputRows[i], IntputColums[i], IntputAngles[i], double.Parse(strdb[1]), double.Parse(strdb[2]), double.Parse(strdb[3]));

            //    //获取矩形的位置信息
            //    HOperatorSet.SmallestRectangle2(ho_RegionAffineTrans, out HTuple row, out HTuple col, out HTuple phi, out HTuple length1, out HTuple length2);

            //    var lineTuple = new HTuple[] { row, col, phi, length1, length2 };// 提取开始坐标和结束坐标

            //    HDrawingObject lineObj = HDrawingObject.CreateDrawingObject(HDrawingObject.HDrawingObjectType.RECTANGLE2, lineTuple);// 绘制线段
            //    //设置线的颜色
            //    try
            //    {
            //        lineObj.SetDrawingObjectParams("color", HideOutputlineColor.ToLower());
            //    }
            //    catch
            //    {
            //        lineObj.SetDrawingObjectParams("color", "red");
            //        throw new Exception("该线条不支持此颜色以为你选择默认颜色!");
            //    }
            //    //永久保留该对象,不然会被垃圾回收机制回收
            //    lines.Add(new HDrawingObjectEx
            //    {
            //        HDrawingObject = lineObj,
            //        hTuples = lineTuple
            //    });
            //    //增加这个对象到指定Halcon窗口
            //    hw.HalconWindow.AttachDrawingObjectToWindow(lineObj);
            //}

            //*-------------------------------------------------------*//
            /// <summary>z
            /// 创建多个旋转矩形,根据模板的识别出的数据决定
            /// </summary>
            //public void DrawRectangle2s(double[] IntputColums, double[] IntputRows, double[] IntputAngles, double PianYiPhi)
            //{
            //    lines.Clear();
            //    for (int i = 0; i < IntputColums.Length; i++)
            //    {
            //        //定义绘制线的开始坐标与结束坐标 *修改这里
            //        var lineTuple = firstLine;
            //        //创建线的对象
            //        HOperatorSet.GenRectangle2(out HObject hLine, lineTuple[0], lineTuple[1], lineTuple[2], lineTuple[3], lineTuple[4]);


            //        HObject ho_RegionAffineTrans = UtiyHalcon.MatrixCalculate(hLine, IntputRows[i], IntputColums[i], IntputAngles[i], firstModel_x, firstModel_y, firstModel_phi);

            //        HOperatorSet.SmallestRectangle2(ho_RegionAffineTrans, out HTuple row, out HTuple col, out HTuple phi, out HTuple length1, out HTuple length2);

            //        lineTuple = new HTuple[] { row, col, phi, length1, length2 };// 提取开始坐标和结束坐标

            //        HDrawingObject lineObj = HDrawingObject.CreateDrawingObject(HDrawingObject.HDrawingObjectType.RECTANGLE2, lineTuple);// 绘制线段
            //                                                                                                                             //设置线的颜色
            //        try
            //        {
            //            lineObj.SetDrawingObjectParams("color", HideOutputlineColor.ToLower());
            //        }
            //        catch
            //        {
            //            lineObj.SetDrawingObjectParams("color", "red");
            //            throw new Exception("该线条不支持此颜色以为你选择默认颜色!");
            //        }
            //        //永久保留该对象,不然会被垃圾回收机制回收
            //        lines.Add(new HDrawingObjectEx
            //        {
            //            HDrawingObject = lineObj,
            //            hTuples = lineTuple
            //        });
            //        //增加这个对象到指定Halcon窗口
            //        hw.HalconWindow.AttachDrawingObjectToWindow(lineObj);
            //    }
            //}
        }
    }
}
